package com.frogs.ucenter.util.task;

import java.math.BigDecimal;
import java.util.Arrays;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.frogs.system.web.api.entity.TaskActionMessageMqEntity;

/**
 * 任务消息发送辅助类
 *
 * @author lijian
 * @version 2015年9月14日 - 上午10:34:08
 */
@Component("taskActionMqSend")
public class TaskActionMqSend {
	private static final Logger log = LoggerFactory.getLogger(TaskActionMqSend.class);
	
	@Resource(name="taskTemplate")
    private JmsTemplate jmsTemplate;
	
	@Async
	public void send(String actionType, BigDecimal money, String remark, int userId, int openPlatformId) {
		TaskActionMessageMqEntity taskActionMessageMqEntity = new TaskActionMessageMqEntity();
		taskActionMessageMqEntity.setActionType(actionType);
		taskActionMessageMqEntity.setMoney(money);
		taskActionMessageMqEntity.setRemark(remark);
		taskActionMessageMqEntity.setUserId(userId);
		taskActionMessageMqEntity.setOpenPlatformId(openPlatformId);;
		this.sendToQueue(taskActionMessageMqEntity);
    }
	
	protected void sendToQueue(final TaskActionMessageMqEntity taskActionMessageMqEntity){
		
		Session session = null;
		Connection connection = null;
		try {
			connection = jmsTemplate.getConnectionFactory().createConnection();//创建连接
			session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);//创建session
			String queueName = jmsTemplate.getDefaultDestinationName();//获取队列名
			Destination destination = session.createQueue(queueName);//创建队列
			Message message = session.createObjectMessage(taskActionMessageMqEntity);//创建发送内容
			session.createProducer(destination).send(message, DeliveryMode.PERSISTENT, 5, 5000000L);
		} catch (Exception e) {
			log.error("func[{}] exception[{} - {}] desc[fail]",//
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} finally {  
            try {  
                if (null != connection)  
                    connection.close();  
                if (null != session)  
                	session.close();  
            } catch (Throwable e) { 
            	log.error("func[{}] exception[{} - {}] desc[fail]",//
    					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
            }  
        } 
		
	}
	
}
